package com.kite.music;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ViewUtil {
    private WebView webview;
    private Activity activity;
    private Context context;

    // 对话框管理器，用于跟踪和管理对话框
    private final Map<String, AlertDialog> dialogMap = new HashMap<>();
    private final Map<String, ProgressDialog> progressDialogMap = new HashMap<>();

    // 单选对话框选中项跟踪
    private int selectedItem = -1;

    // 异步执行器
    private final ExecutorService asyncExecutor = Executors.newCachedThreadPool();

    public ViewUtil(WebView webview, Activity activity, Context context){
        this.webview = webview;
        this.activity = activity;
        this.context = context;
    }

    // 显示简单提示弹窗 - 重构版本，返回JSON格式结果
    @JavascriptInterface
    public String showAlertDialogWithCallback(String title, String message, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);

                if (title != null && !title.trim().isEmpty()) {
                    builder.setTitle(title);
                }

                builder.setMessage(message != null ? message : "")
                       .setPositiveButton("确定", (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createDialogResult(true, "ok"));
                           }
                       })
                       .setCancelable(true)
                       .setOnCancelListener(dialog -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createDialogResult(false, "cancel"));
                           }
                       });

                AlertDialog dialog = builder.show();

                // 返回对话框引用ID，用于后续控制
                String dialogId = "dialog_" + System.currentTimeMillis();
                dialogMap.put(dialogId, dialog);

                return createSuccessResponse(dialogId);

            } catch (Exception e) {
                return createErrorResponse("显示对话框失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public void showAlertDialog(String title, String message) {
        showAlertDialogWithCallback(title, message, null);
    }

    // 显示确认弹窗 - 重构版本，支持回调机制
    @JavascriptInterface
    public String showConfirmDialogWithCallback(String title, String message, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);

                if (title != null && !title.trim().isEmpty()) {
                    builder.setTitle(title);
                }

                builder.setMessage(message != null ? message : "")
                       .setPositiveButton("确定", (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createDialogResult(true, "confirm"));
                           }
                       })
                       .setNegativeButton("取消", (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createDialogResult(false, "cancel"));
                           }
                       })
                       .setCancelable(true)
                       .setOnCancelListener(dialog -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createDialogResult(false, "dismiss"));
                           }
                       });

                AlertDialog dialog = builder.show();

                // 返回对话框引用ID，用于后续控制
                String dialogId = "dialog_" + System.currentTimeMillis();
                dialogMap.put(dialogId, dialog);

                return createSuccessResponse(dialogId);

            } catch (Exception e) {
                return createErrorResponse("显示确认对话框失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public void showConfirmDialog(String title, String message, String callbackFunction) {
        showConfirmDialogWithCallback(title, message, callbackFunction);
    }

    // 显示列表选择弹窗 - 重构版本，支持回调机制
    @JavascriptInterface
    public String showListDialogWithCallback(String title, String itemsJson, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                // 解析选项列表
                String[] items = parseItemsArray(itemsJson);
                if (items == null || items.length == 0) {
                    return createErrorResponse("选项列表不能为空");
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);

                if (title != null && !title.trim().isEmpty()) {
                    builder.setTitle(title);
                }

                builder.setItems(items, (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createListDialogCallbackResult(true, which, items[which], "select"));
                           }
                       })
                       .setCancelable(true)
                       .setOnCancelListener(dialog -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createListDialogCallbackResult(false, -1, "", "cancel"));
                           }
                       });

                AlertDialog dialog = builder.show();

                // 返回对话框引用ID，用于后续控制
                String dialogId = "dialog_" + System.currentTimeMillis();
                dialogMap.put(dialogId, dialog);

                return createSuccessResponse(dialogId);

            } catch (Exception e) {
                return createErrorResponse("显示列表对话框失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public void showListDialog(String title, String itemsJson, String callbackFunction) throws Exception {
        showListDialogWithCallback(title, itemsJson, callbackFunction);
    }

    // 显示单选列表弹窗 - 重构版本，支持回调机制
    @JavascriptInterface
    public String showSingleChoiceDialogWithCallback(String title, String itemsJson, int checkedItem, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                // 解析选项列表
                String[] items = parseItemsArray(itemsJson);
                if (items == null || items.length == 0) {
                    return createErrorResponse("选项列表不能为空");
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);

                if (title != null && !title.trim().isEmpty()) {
            builder.setTitle(title);
        }

                builder.setSingleChoiceItems(items, checkedItem, (dialog, which) -> {
                           // 更新选中项
                           selectedItem = which;
                       })
                       .setPositiveButton("确定", (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createListDialogCallbackResult(true, selectedItem, items[selectedItem], "confirm"));
                           }
                       })
                       .setNegativeButton("取消", (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createListDialogCallbackResult(false, -1, "", "cancel"));
                           }
                       })
                       .setCancelable(true)
                       .setOnCancelListener(dialog -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createListDialogCallbackResult(false, -1, "", "dismiss"));
                           }
                       });

                AlertDialog dialog = builder.show();

                // 返回对话框引用ID，用于后续控制
                String dialogId = "dialog_" + System.currentTimeMillis();
                dialogMap.put(dialogId, dialog);

                return createSuccessResponse(dialogId);

            } catch (Exception e) {
                return createErrorResponse("显示单选对话框失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public void showSingleChoiceDialog(String title, String itemsJson, int checkedItem, String callbackFunction) {
        showSingleChoiceDialogWithCallback(title, itemsJson, checkedItem, callbackFunction);
    }

    // 显示进度弹窗 - 重构版本，返回JSON格式结果
    @JavascriptInterface
    public String showProgressDialogWithCallback(String title, String message, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                ProgressDialog progressDialog = new ProgressDialog(activity);

                if (title != null && !title.trim().isEmpty()) {
                    progressDialog.setTitle(title);
                }

                progressDialog.setMessage(message != null ? message : "请稍候...");
                progressDialog.setCancelable(false);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.show();

                // 返回对话框引用ID，用于后续控制
                String dialogId = "progress_" + System.currentTimeMillis();
                progressDialogMap.put(dialogId, progressDialog);

                // 如果有回调函数，异步执行任务
                if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                    executeAsync(() -> {
                        callJavaScriptCallback(callbackFunction, createProgressDialogCallbackResult(true, dialogId, "progress"));
                    });
                }

                return createSuccessResponse(dialogId);

            } catch (Exception e) {
                return createErrorResponse("显示进度对话框失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public String showProgressDialog(String title, String message) {
        return showProgressDialogWithCallback(title, message, null);
    }

    // 显示Toast提示 - 重构版本，支持回调
    @JavascriptInterface
    public String showToastWithCallback(String message, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                if (message == null || message.trim().isEmpty()) {
                    return createErrorResponse("Toast消息不能为空");
                }

                Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
                toast.show();

                // 如果有回调函数，异步执行
                if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                    executeAsync(() -> {
                        callJavaScriptCallback(callbackFunction, createToastCallbackResult(true, message, "short"));
                    });
                }

                return createSuccessResponse("Toast显示成功");

            } catch (Exception e) {
                return createErrorResponse("Toast显示失败: " + e.getMessage());
            }
        });
    }

    // 显示长时Toast提示 - 重构版本，支持回调
    @JavascriptInterface
    public String showLongToastWithCallback(String message, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                if (message == null || message.trim().isEmpty()) {
                    return createErrorResponse("Toast消息不能为空");
                }

                Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
                toast.show();

                // 如果有回调函数，异步执行
                if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                    executeAsync(() -> {
                        callJavaScriptCallback(callbackFunction, createToastCallbackResult(true, message, "long"));
                    });
                }

                return createSuccessResponse("长Toast显示成功");

            } catch (Exception e) {
                return createErrorResponse("长Toast显示失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public void showToast(String message) {
        showToastWithCallback(message, null);
    }

    @JavascriptInterface
    public void showLongToast(String message) {
        showLongToastWithCallback(message, null);
    }

    // 显示输入对话框 - 新增功能
    @JavascriptInterface
    public String showInputDialog(String title, String hint, String defaultValue, String callbackFunction) {
        return executeUIThread(() -> {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);

                if (title != null && !title.trim().isEmpty()) {
                    builder.setTitle(title);
                }

                // 创建输入框
                final EditText input = new EditText(activity);
                input.setHint(hint != null ? hint : "请输入内容");
                input.setText(defaultValue != null ? defaultValue : "");

                builder.setView(input)
                       .setPositiveButton("确定", (dialog, which) -> {
                           String inputText = input.getText().toString();
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createInputDialogCallbackResult(true, inputText, "confirm"));
                           }
                       })
                       .setNegativeButton("取消", (dialog, which) -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createInputDialogCallbackResult(false, "", "cancel"));
                           }
                       })
                       .setCancelable(true)
                       .setOnCancelListener(dialog -> {
                           if (callbackFunction != null && !callbackFunction.trim().isEmpty()) {
                               callJavaScriptCallback(callbackFunction, createInputDialogCallbackResult(false, "", "dismiss"));
                           }
                       });

                AlertDialog dialog = builder.show();

                // 返回对话框引用ID，用于后续控制
                String dialogId = "input_" + System.currentTimeMillis();
                dialogMap.put(dialogId, dialog);

                return createSuccessResponse(dialogId);

            } catch (Exception e) {
                return createErrorResponse("显示输入对话框失败: " + e.getMessage());
            }
        });
    }

    // 测试 - 重构版本，返回JSON格式
    @JavascriptInterface
    public String testViewUtil(){
        return executeUIThread(() -> {
            try {
                // 测试Toast
                Toast.makeText(context, "ViewUtil测试成功", Toast.LENGTH_SHORT).show();

                return createSuccessResponse("ViewUtil测试通过");
            } catch (Exception e) {
                return createErrorResponse("ViewUtil测试失败: " + e.getMessage());
            }
        });
    }

    // 兼容旧接口的方法
    @JavascriptInterface
    public boolean test(){
        try {
            String result = testViewUtil();
            JSONObject response = new JSONObject(result);
            return response.getBoolean("success");
        } catch (Exception e) {
            return false;
        }
    }

    // ============ 辅助方法 ============

    /**
     * 在UI线程中执行操作
     */
    private String executeUIThread(Callable<String> operation) {
        try {
            if (activity != null) {
                activity.runOnUiThread(() -> {
                    try {
                        operation.call();
                    } catch (Exception e) {
                        // 忽略UI线程中的异常，由调用者处理
                    }
                });
            }
            return createSuccessResponse("操作已提交到UI线程");
        } catch (Exception e) {
            return createErrorResponse("UI线程执行失败: " + e.getMessage());
        }
    }

    /**
     * 异步执行操作
     */
    private void executeAsync(Runnable task) {
        asyncExecutor.submit(() -> {
            try {
                task.run();
            } catch (Exception e) {
                // 记录异步执行异常
                android.util.Log.e("ViewUtil", "异步任务执行失败", e);
            }
        });
    }

    /**
     * 安全的JavaScript回调方法
     */
    private void callJavaScriptCallback(final String callbackFunction, final String result) {
        if (callbackFunction == null || callbackFunction.trim().isEmpty()) {
            return;
        }

        if (activity == null || webview == null) {
            android.util.Log.w("ViewUtil", "Activity或WebView为空，无法执行回调");
            return;
        }

        activity.runOnUiThread(() -> {
            try {
                String jsCode = String.format("%s(%s)",
                        callbackFunction,
                        escapeJavaScriptString(result));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    // 使用更安全的evaluateJavascript方法
                    webview.evaluateJavascript(jsCode, null);
                } else {
                    // 回退到loadUrl，但确保正确转义
                    String safeJsCode = "javascript:try{" + jsCode + ";}catch(e){console.error('ViewUtil callback error:', e);}";
                    webview.loadUrl(safeJsCode);
                }
            } catch (Exception e) {
                android.util.Log.e("ViewUtil", "JavaScript回调失败", e);
            }
        });
    }

    /**
     * 创建对话框结果对象
     */
    private String createDialogResult(boolean success, String action) {
        try {
            JSONObject result = new JSONObject();
            result.put("success", success);
            result.put("action", action);
            result.put("timestamp", System.currentTimeMillis());
            return result.toString();
        } catch (Exception e) {
            return "{\"success\":" + success + ",\"action\":\"" + action + "\"}";
        }
    }

    /**
     * 创建列表选择对话框回调结果（带异常处理）
     */
    private String createListDialogCallbackResult(boolean success, int selectedIndex, String selectedText, String action) {
        try {
            JSONObject result = new JSONObject();
            result.put("success", success);
            result.put("selectedIndex", selectedIndex);
            result.put("selectedText", selectedText != null ? selectedText : "");
            result.put("action", action);
            result.put("timestamp", System.currentTimeMillis());
            return result.toString();
        } catch (Exception e) {
            return "{\"success\":" + success + ",\"selectedIndex\":" + selectedIndex +
                   ",\"selectedText\":\"" + (selectedText != null ? escapeJson(selectedText) : "") +
                   "\",\"action\":\"" + action + "\"}";
        }
    }

    /**
     * 创建输入对话框回调结果（带异常处理）
     */
    private String createInputDialogCallbackResult(boolean success, String text, String action) {
        try {
            JSONObject result = new JSONObject();
            result.put("success", success);
            result.put("text", text != null ? text : "");
            result.put("action", action);
            result.put("timestamp", System.currentTimeMillis());
            return result.toString();
        } catch (Exception e) {
            return "{\"success\":" + success + ",\"text\":\"" +
                   (text != null ? escapeJson(text) : "") + "\",\"action\":\"" + action + "\"}";
        }
    }

    /**
     * 创建进度对话框回调结果（带异常处理）
     */
    private String createProgressDialogCallbackResult(boolean success, String dialogId, String type) {
        try {
            JSONObject result = new JSONObject();
            result.put("success", success);
            result.put("dialogId", dialogId != null ? dialogId : "");
            result.put("type", type != null ? type : "");
            result.put("timestamp", System.currentTimeMillis());
            return result.toString();
        } catch (Exception e) {
            return "{\"success\":" + success + ",\"dialogId\":\"" +
                   (dialogId != null ? escapeJson(dialogId) : "") +
                   "\",\"type\":\"" + (type != null ? type : "") + "\"}";
        }
    }

    /**
     * 创建Toast回调结果（带异常处理）
     */
    private String createToastCallbackResult(boolean success, String message, String duration) {
        try {
            JSONObject result = new JSONObject();
            result.put("success", success);
            result.put("message", message != null ? message : "");
            result.put("duration", duration != null ? duration : "");
            result.put("timestamp", System.currentTimeMillis());
            return result.toString();
        } catch (Exception e) {
            return "{\"success\":" + success + ",\"message\":\"" +
                   (message != null ? escapeJson(message) : "") +
                   "\",\"duration\":\"" + (duration != null ? duration : "") + "\"}";
        }
    }

    /**
     * 创建成功响应
     */
    private String createSuccessResponse(String data) {
        try {
            JSONObject response = new JSONObject();
            response.put("success", true);
            response.put("data", data);
            response.put("timestamp", System.currentTimeMillis());
            return response.toString();
        } catch (Exception e) {
            return "{\"success\":true,\"data\":\"" + escapeJson(data) + "\"}";
        }
    }

    /**
     * 创建错误响应
     */
    private String createErrorResponse(String error) {
        try {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("error", error);
            response.put("timestamp", System.currentTimeMillis());
            return response.toString();
        } catch (Exception e) {
            return "{\"success\":false,\"error\":\"" + escapeJson(error) + "\"}";
        }
    }

    /**
     * 转义JSON字符串中的特殊字符
     */
    private String escapeJson(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\\", "\\\\")
                   .replace("\"", "\\\"")
                   .replace("\b", "\\b")
                   .replace("\f", "\\f")
                   .replace("\n", "\\n")
                   .replace("\r", "\\r")
                   .replace("\t", "\\t");
    }

    /**
     * 转义JavaScript字符串中的特殊字符
     */
    private String escapeJavaScriptString(String value) {
        if (value == null) {
            return "null";
        }

        String escaped = escapeJson(value);
        return "\"" + escaped + "\"";
    }

    /**
     * 解析选项数组
     */
    private String[] parseItemsArray(String itemsJson) {
        if (itemsJson == null || itemsJson.trim().isEmpty()) {
            return null;
        }

        try {
            // 尝试解析为JSON数组
            JSONArray jsonArray = new JSONArray(itemsJson);
            String[] items = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                items[i] = jsonArray.getString(i);
            }
            return items;
        } catch (Exception e) {
            // 如果不是JSON，假设是逗号分隔的字符串
            return itemsJson.split(",");
        }
    }

    /**
     * 关闭指定对话框
     */
    @JavascriptInterface
    public String dismissDialog(String dialogId) {
        return executeUIThread(() -> {
            try {
                AlertDialog dialog = dialogMap.get(dialogId);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                    dialogMap.remove(dialogId);
                    return createSuccessResponse("对话框已关闭");
                }

                ProgressDialog progressDialog = progressDialogMap.get(dialogId);
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialogMap.remove(dialogId);
                    return createSuccessResponse("进度对话框已关闭");
                }

                return createErrorResponse("对话框未找到或已关闭");
            } catch (Exception e) {
                return createErrorResponse("关闭对话框失败: " + e.getMessage());
            }
        });
    }

    /**
     * 更新进度对话框消息
     */
    @JavascriptInterface
    public String updateProgressDialog(String dialogId, String message) {
        return executeUIThread(() -> {
            try {
                ProgressDialog progressDialog = progressDialogMap.get(dialogId);
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.setMessage(message != null ? message : "请稍候...");
                    return createSuccessResponse("进度消息已更新");
                }
                return createErrorResponse("进度对话框未找到或已关闭");
            } catch (Exception e) {
                return createErrorResponse("更新进度消息失败: " + e.getMessage());
            }
        });
    }

    /**
     * 获取活跃对话框列表
     */
    @JavascriptInterface
    public String getActiveDialogs() {
        return executeUIThread(() -> {
            try {
                JSONObject activeDialogs = new JSONObject();

                if (!dialogMap.isEmpty()) {
                    JSONArray alertDialogs = new JSONArray();
                    for (String id : dialogMap.keySet()) {
                        alertDialogs.put(id);
                    }
                    activeDialogs.put("alertDialogs", alertDialogs);
                }

                if (!progressDialogMap.isEmpty()) {
                    JSONArray progressDialogs = new JSONArray();
                    for (String id : progressDialogMap.keySet()) {
                        progressDialogs.put(id);
                    }
                    activeDialogs.put("progressDialogs", progressDialogs);
                }

                return createSuccessResponse(activeDialogs.toString());
            } catch (Exception e) {
                return createErrorResponse("获取活跃对话框失败: " + e.getMessage());
            }
        });
    }

    /**
     * 清理所有对话框
     */
    @JavascriptInterface
    public String cleanupDialogs() {
        return executeUIThread(() -> {
            try {
                int dialogCount = 0;

                // 关闭所有AlertDialog
                for (AlertDialog dialog : dialogMap.values()) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                        dialogCount++;
                    }
                }
                dialogMap.clear();

                // 关闭所有ProgressDialog
                for (ProgressDialog dialog : progressDialogMap.values()) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                        dialogCount++;
                    }
                }
                progressDialogMap.clear();

                return createSuccessResponse("已清理 " + dialogCount + " 个对话框");
            } catch (Exception e) {
                return createErrorResponse("清理对话框失败: " + e.getMessage());
            }
        });
    }

    /**
     * 销毁资源
     */
    public void destroy() {
        try {
            // 清理所有对话框
            cleanupDialogs();

            // 关闭异步执行器
            if (asyncExecutor != null && !asyncExecutor.isShutdown()) {
                asyncExecutor.shutdown();
            }

            // 清空引用
            dialogMap.clear();
            progressDialogMap.clear();

        } catch (Exception e) {
            android.util.Log.e("ViewUtil", "销毁ViewUtil失败", e);
        }
    }
}